﻿using System.Web.Mvc;
using Inovout.Security;
using System.Web.Security;
using System.Web;
using System.Threading;
using System.Security.Principal;

namespace Inovout.Web.Filters
{
    public class AuthenticateFilter : IAuthorizationFilter
    {
        public AuthenticateFilter(IUserService userService)
        {
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var context = filterContext.HttpContext;

            if (context.User != null && context.User.Identity.IsAuthenticated)
            {
                var userPrincipal = AccountAuthentication.GetPrincipal(context.User.Identity.Name);

                if (userPrincipal == null)
                {
                    FormsAuthentication.SignOut();
                }
                else
                {
                    AuthenticateAs(context, userPrincipal);
                }
            }
            else
            {
                AuthenticateAs(context, AccountAuthentication.AnonymousUserPrincipal);
            }



        }

        private void AuthenticateAs(HttpContextBase context, IPrincipal user)
        {
            Thread.CurrentPrincipal = context.User = user;
        }
    }
}
